package com.mdp.tpa.wechat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;  
  
/** 
 * 说明 
 * 利用httpclient下载文件 
 * maven依赖 
 * <dependency> 
*           <groupId>org.apache.httpcomponents</groupId> 
*           <artifactId>httpclient</artifactId> 
*           <version>4.0.1</version> 
*       </dependency> 
*  可下载http文件、图片、压缩文件 
*  bug：获取response header中Content-Disposition中filename中文乱码问题 
 * @author tanjundong 
 * 
 */  
public class HttpDownload {  
	public static Log log=LogFactory.getLog(HttpDownload.class);
  
    public static final int cache = 10 * 1024;  
    public static final boolean isWindows;  
    public static final String splash;  
    public static final String root;  
    static {  
        if (System.getProperty("os.name") != null && System.getProperty("os.name").toLowerCase().contains("windows")) {  
            isWindows = true;  
            splash = "\\";  
            root="D:\\swap\\file";  
        } else {  
            isWindows = false;  
            splash = "/";  
            root="/swap/file";  
        }  
    }  
      
    /** 
     * 根据url下载文件，文件名从response header头中获取 
     * @param url 
     * @return 
     */  
    public static String download(String url) {  
        return download(url, null,null);  
    }  
  
    /** 
     * 根据url下载文件，保存到filepath中 
     * @param url 
     * @param fileSaveDir
     * @param fileName
     * @return 
     */  
    public static String download(String url, String fileSaveDir,String fileName) {  
            HttpClient client = new DefaultHttpClient();  
            HttpGet httpget = new HttpGet(url);  
            HttpResponse response;
			try {
				response = client.execute(httpget);
				return download(response,fileSaveDir,fileName); 
			} catch (ClientProtocolException e) {
				 log.error("",e);
				 throw new RuntimeException(e.getMessage());
			} catch (IOException e) {
				 log.error("",e);
				 throw new RuntimeException(e.getMessage());
			} 
    }
    /** 
     * 根据url下载文件，保存到filepath中
     * @return 
     */  
    public static String download( HttpResponse response, String fileSaveDir,String fileName) {  
    	  String filePathAndName=null;
        try {  
        	String contentType=response.getFirstHeader("Content-Type").getValue();
        	String fileDot="";
        	if(contentType!=null){
        		String fileDots[]=contentType.split("/");
        		if(fileDots.length>0){
        			fileDot=fileDots[1];
        		}
        		
        	}
            HttpEntity entity = response.getEntity();  
            InputStream is = entity.getContent();  
            String fileName2=fileName;
          
            if (fileSaveDir == null || "".equals(fileSaveDir))  {
            	fileSaveDir = getFilePath(response);  
            	
            }
            if( fileName==null || "".equals(fileName)){
            	fileName2=getFileName(response);
            } 
            filePathAndName=fileSaveDir+splash+fileName2;
            if(!fileName2.contains(".")){
            	filePathAndName=filePathAndName+"."+fileDot;
            }
            File file = new File(filePathAndName);  
            file.getParentFile().mkdirs();  
            FileOutputStream fileout = new FileOutputStream(file);  
            /** 
             * 根据实际运行效果 设置缓冲区大小 
             */  
            byte[] buffer=new byte[cache];  
            int ch = 0;  
            while ((ch = is.read(buffer)) != -1) {  
                fileout.write(buffer,0,ch);  
            }  
            is.close();  
            fileout.flush();  
            fileout.close();  
  
        } catch (Exception e) {  
        	log.error("",e);
        	throw new RuntimeException(e.getMessage());
        }  
        return filePathAndName;  
    }  
    /** 
     * 获取response要下载的文件的默认路径 
     * @param response 
     * @return 
     */  
    public static String getFilePath(HttpResponse response) {  
        String filepath = root + splash;   
        return filepath;  
    }  
    /** 
     * 获取response header中Content-Disposition中的filename值 
     * @param response 
     * @return 
     */  
    public static String getFileName(HttpResponse response) {  
        Header contentHeader = response.getFirstHeader("Content-Disposition");  
        String filename = null;  
        if (contentHeader != null) {  
            HeaderElement[] values = contentHeader.getElements();  
            if (values.length == 1) {  
                NameValuePair param = values[0].getParameterByName("filename");  
                if (param != null) {  
                    try {  
                        //filename = new String(param.getValue().toString().getBytes(), "utf-8");  
                        //filename=URLDecoder.decode(param.getValue(),"utf-8");  
                        filename = param.getValue();  
                        filename=filename.replaceAll("\\\\", "");
                    } catch (Exception e) {  
                    	
                    	log.error("",e);
                    	//throw new RuntimeException(e.getMessage());
                    }  
                }  
            }  
        }
        if(filename==null){
        	filename=getRandomFileName();
        }
        return filename;  
    }  
    /** 
     * 获取随机文件名 
     * @return 
     */  
    public static String getRandomFileName() {  
        return String.valueOf(System.currentTimeMillis());  
    }  
    public static void outHeaders(HttpResponse response) {  
        Header[] headers = response.getAllHeaders();  
        for (int i = 0; i < headers.length; i++) {  
            //System.out.println(headers[i]);  
        }  
    }  
    public static void main(String[] args) {  
//      String url = "http://bbs.btwuji.com/job.php?action=download&pid=tpc&tid=320678&aid=216617";  
        String url="http://img.zcool.cn/community/0142135541fe180000019ae9b8cf86.jpg@1280w_1l_2o_100sh.png";  
//      String filepath = "D:\\test\\a.torrent";  
        String filepath = "D:\\test\\a.jpg";  
        HttpDownload.download(url);  
    }  
}